<template>
  <div class="table-all">
    <!-- 搜索区 -->
    <div class="app-container search-box">
      <SearchForm
        :form="searchData.form"
        :options="searchData.options"
        @searchUpdate="search"
        @resetSearchData="resetSearchData"
      ></SearchForm>
    </div>
    <!-- 按钮区 -->
    <div class="app-container table-box">
      <div class="table-main">
        <!-- 表格 -->
        <v-table
          :title="this.$commonJs.getModeName(this.$route.path) + '预警信息'"
          v-if="tableMainHeight>0"
          :table-columns="tableColumns"
          :table-data="tableData"
          :loading="loading"
          :is-index="true"
          ref="table"
          :maxHeight="tableMainHeight">
          <template #topButtonList>
            <ButtonForm :buttonList="buttonList" @clickButton="clickButton"></ButtonForm>
          </template>
          <template #warnType="scope">
            {{ getDictValue(scope.row.warnType, warnTypeOptions) }}
          </template>
          <template #warnLevel="scope">
            {{ getDictValue(scope.row.warnLevel, warnLevelOptions) }}
          </template>
          <template #status="scope">
            {{ getDictValue(scope.row.status, statusOptions) }}
          </template>
          <template #disposeStatus="scope">
            {{ scope.row.disposeStatus ? getDictValue(scope.row.disposeStatus, disposeStatusOptions) : "未处置" }}
          </template>
          <template #isTimeout="scope">
            {{ getDictValue(scope.row.isTimeout, isTimeoutOptions) }}
          </template>
          <template #superviseState="scope">
            {{getDictValue(scope.row.superviseState, superviseStateOptions)}}
          </template>
          <template #operation="scope">
            <span v-if="scope.row.superviseOrderNum==null||scope.row.superviseOrderNum==''" >
              <a v-if="$commonJs.showUrgeButton(scope.row.disposeStatus,'warning')"
                 v-hasPermission="['alarmWarning:urge']" class="table-btn-edit table-operation"
                 @click="handleUrge(scope.row)">{{$t('table.urge')}}</a>
            </span>
            <a v-if="scope.row.disposeStatus!=2"
               v-hasPermission="['alarmWarning:add']" class="table-btn-edit table-operation"
               @click="handleEdit(scope.row)">{{$t('table.edit')}}</a>
            <a v-if="scope.row.disposeStatus!=2"
               v-hasPermission="['alarmWarning:deal']" class="table-btn-edit table-operation"
               @click="handleDispose(scope.row)">{{$t('table.deal')}}</a>
            <a v-hasPermission="['alarmWarning:add']" class="table-btn-view table-operation"
               @click="handleDetail(scope.row)">{{$t('table.view')}}</a>
            <a v-hasPermission="['alarmWarning:delete']" class="table-btn-delete table-operation"
               @click="singleDelete(scope.row)">{{$t('table.delete')}}</a>
          </template>
        </v-table>
      </div>
      <div class="table-page">
        <!-- 页码 -->
        <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize"
                    @pagination="search"/>
      </div>
    </div>
    <!-- 详情 -->
    <detailDialog :dialog-visible="detailDialogShow"
                  @success="editSuccess"
                  @close="editClose"
                  :superviseOrderNum="curSuperviseOrderNum"
                  :curDisposeStatus = "curDisposeStatus"
                  :openType="detailOpenType"
                  :id="detailId"
                  :title="detailTitle"
    ></detailDialog>
  </div>
</template>

<script>
import {
  alarmWarningPage,
  alarmWarningExport,
  alarmWarningDelete,
  orderPush
} from '@/api/alarm/warning'
import SearchForm from '@/components/searchForm'
import ButtonForm from '@/components/ButtonForm'
import VTable from '@/components/VTable'
import Pagination from '@/components/Pagination'
import detailDialog from './detail.vue'

export default {
  components: {
    VTable, Pagination, detailDialog, SearchForm, ButtonForm
  },
  data() {
    return {
      modeType: '',
      title: '',

      tableColumns: [
        {
          prop: 'identificationCode',
          label: '标识码',
          minWidth: '150',
          slotname: 'identificationCode',
          options: {}
        },
        {
          prop: 'warnName',
          label: '预警名称',
          minWidth: '150',
          slotname: 'warnName',
          options: {}
        },
        {
          prop: 'warnType',
          label: '预警类型',
          minWidth: '150',
          slotname: 'warnType',
          options: {}
        },
        {
          prop: 'warnLevel',
          label: '预警级别',
          minWidth: '150',
          slotname: 'warnLevel',
          options: {}
        },
        {
          prop: 'status',
          label: '预警状态',
          minWidth: '150',
          slotname: 'status',
          options: {}
        },
        {
          prop: 'address',
          label: '详细地址',
          minWidth: '150',
          slotname: 'address',
          options: {}
        },
        {
          prop: 'disposeStatus',
          label: '处置状态',
          minWidth: '150',
          slotname: 'disposeStatus',
          options: {}
        },
        {
          prop: 'isTimeout',
          label: '是否按时处置',
          minWidth: '150',
          slotname: 'isTimeout',
          options: {}
        },
        {
          prop: 'areaCode',
          label: '区域',
          minWidth: '150',
          slotname: 'areaCode',
          options: {}
        },
        {
          prop: 'warnReportTime',
          label: '预警上报时间',
          minWidth: '150',
          slotname: 'warnReportTime',
          options: {}
        },
        {
          prop: 'superviseState',
          label: '督办状态',
          minWidth: '100',
          slotname: 'superviseState',
          options: {}
        },
        {
          prop: 'operation',
          label: '操作',
          width: '200',
          align: 'center',
          slotname: 'operation',
          overflow: false,
          fixed: 'right'
        }
      ],
      tableData: [],
      selection: [],
      loading: false,
      total: 1,
      pageNum: 1,
      pageSize: 10,
      detailOpenType: "add",
      detailDialogShow: false,
      detailId: "",
      detailTitle: this.title + "新增",
      curSuperviseOrderNum:"",
      curDisposeStatus:"",
      dict: {},
      searchData: {
        form: {
          modeType: this.modeType,
          warnName:'',
          warnReportTimeRange:'',
          warnType: '',
          status: '',
          disposeStatus: '',
          provinceCode: '',
          cityCode: '',
          countyCode: '',
          areaCode: '',
          isTimeout:'',
          selectAreaCode: [],
        },
        options: [
          {
            title:'预警名称',
            key: "warnName",
            type: "text",
          },
          {
            title: '预警类型',
            key: "warnType",
            type: "select",
            multiple: false,
            option: {
              data: this.warnTypeOptions,
              props: {
                key: "id", // 指定key对应data的字段
                label: "label", // 指定label对应data的字段
                value: "value", // 指定value对应data的字段
              },
            },
          },
          {
            title: '预警状态',
            key: "status",
            type: "select",
            multiple: false,
            option: {
              data: this.statusOptions,
              props: {
                key: "id", // 指定key对应data的字段
                label: "label", // 指定label对应data的字段
                value: "value", // 指定value对应data的字段
              },
            },
          },
          {
            title: '处置状态',
            key: "disposeStatus",
            type: "select",
            multiple: false,
            option: {
              data: this.disposeStatusOptions,
              props: {
                key: "id", // 指定key对应data的字段
                label: "label", // 指定label对应data的字段
                value: "value", // 指定value对应data的字段
              },
            },
          },
          {
            title: "区域",
            key: "selectAreaCode",
            type: "gdAreaSelect",
            changeFn: this.searchAreacodeHandle, //如需对区域数据做更多的处理，可在这里定义方法
          },
          {
            title: '预警上报时间',
            key: "warnReportTimeRange",
            type: "date-to-date",
          },
          {
            title: "是否按时处置",
            key: "isTimeout",
            type: "select",
            multiple: false,
            option: {
              data: this.isTimeoutOptions,
              props: {
                key: "id", // 指定key对应data的字段
                label: "label", // 指定label对应data的字段
                value: "value", // 指定value对应data的字段
              },
            },
          },
        ]
      },
      buttonList: [
        {name: '新增', methods: 'handleAdd', type: 'primary', hasPremission:["alarmWarning:add"]},
        // {name: '导入', methods: 'handleImport'},
        {name: '导出数据', methods: 'handleExport', type: 'primary', hasPremission:["alarmWarning:export"]}
      ],
      tableMainHeight: 0,
      // 字典
      modeTypeOptions: [],
      warnTypeOptions: [],
      statusOptions: [],
      disposeStatusOptions: [],
      warnLevelOptions: [],
      isTimeoutOptions:[],
      superviseStateOptions:[],
    }
  },
  watch: {
    // 字典
    'modeType': {
      handler(newVal, oldVal) {
        this.searchData.form.modeType = newVal;
      },
      deep: true,
      immediate: true
    },
    'warnTypeOptions': {
      handler(newVal, oldVal) {
        this.searchData.options.forEach(t => {
          if (t.key == 'warnType') {
            t.option.data = newVal
          }
        })
      },
      deep: true,
      immediate: true
    },
    'statusOptions': {
      handler(newVal, oldVal) {
        this.searchData.options.forEach(t => {
          if (t.key == 'status') {
            t.option.data = newVal
          }
        })
      },
      deep: true,
      immediate: true
    },
    'disposeStatusOptions': {
      handler(newVal, oldVal) {
        this.searchData.options.forEach(t => {
          if (t.key == 'disposeStatus') {
            let temp = newVal.map(t=> t)
            temp.unshift({id: "-1", label: "未处置", value: "-1"})
            temp.unshift({id: "null", label: "全部", value: ""})
            t.option.data = temp
          }
        })
      },
      deep: true,
      immediate: true
    },
    'isTimeoutOptions':{
      handler(newVal, oldVal) {
        this.searchData.options.forEach(t => {
          if (t.key == 'isTimeout') {
            t.option.data = newVal
          }
        })
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    handleUrge(row){
      console.log("督办===>",row)
      this.$confirm('确定督办？', this.$t('common.tips'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      }).then(() => {
        this.loading = true
        var param = {};
        param.orderNum = row.id;
        var backData ={};
        backData.type='3';
        param.backData = JSON.stringify(backData);
        orderPush(param).then(res=>{
          if(res.code==200){
            this.$message({
              message: '督办提交成功',
              type: 'success'
            })
            this.search()
          }else{
            this.$message({
              message: this.$t('tips.systemException'),
              type: 'error'
            })
          }
        }).finally(final=>{
          this.loading = false
        })
      })
    },
    searchAreacodeHandle(arr) {
      //console.log(arr)
      this.searchData.form.provinceCode = arr[0]
      this.searchData.form.cityCode = arr[1]
      this.searchData.form.countyCode = arr[2]
    },
    getCheckBoxValue(value, option) {
      if (!value) {
        return
      }
      let temp = []
      let data = value.split(",")
      data.forEach(t => {
        let item = option.find(x => x.value == t)
        if (item != undefined) {
          temp.push(item.label)
        }
      })
      return temp.join(",")
    },
    getDictValue(value, option) {
      let item = option.find(t => t.value == value)
      if (item != undefined) {
        return item.label
      }
      return value
    },
    editClose() {
      this.detailDialogShow = false
    },
    editSuccess() {
      this.search()
      this.detailDialogShow = false
    },
    search() {
      this.fetch({
        ...this.searchData.form,
      })
    },
    fetch(params = {}) {
      params.pageSize = this.pageSize
      params.pageNum = this.pageNum
      this.loading = true
      params.modeType = this.modeType != '' ? this.modeType : this.$commonJs.getAlarmPathConfig(this.$route.path).modeTypeYj
      alarmWarningPage(params).then(async res => {
        if (res.code == 200) {
          this.total = res.data.total
          let rows = res.data.rows
          for (let item of rows) {
            item.areaCode =await this.$commonJs.getGzAreaName(item.provinceCode, item.cityCode, item.countyCode)
          }
          this.tableData = rows
        } else {
          this.$message({
            message: this.$t('tips.systemException'),
            type: 'error'
          })
        }
      }).finally(final => {
        this.loading = false
      })
    },
    // 重置搜索条件
    resetSearchData() {
      this.searchData.form = {
        modeType: this.modeType,
        warnName:'',
        warnType: '',
        status: '',
        disposeStatus: '',
        provinceCode: '',
        cityCode: '',
        countyCode: '',
        areaCode: '',
        selectAreaCode: [],
        isTimeout:''
      }
    },

    // 触发按钮区域按钮方法
    clickButton(methods) {
      this[methods]()
    },
    handleAdd() {
      this.detailOpenType = "add"
      this.detailTitle = this.title + "新增"
      this.detailDialogShow = true
    },
    handleEdit(row) {
      this.detailId = row.id
      this.detailOpenType = "edit"
      this.detailTitle = this.title + "编辑"
      this.detailDialogShow = true
    },
    handleDetail(row){
      this.detailId = row.id
      this.detailOpenType = "detail"
      this.detailTitle = this.title + "详情"
      this.curSuperviseOrderNum = row.superviseOrderNum
      this.curDisposeStatus = row.disposeStatus
      this.detailDialogShow = true
    },
    handleDispose(row){
      this.detailId = row.id
      this.detailOpenType = "dispose"
      this.detailTitle = this.title + "处置"
      this.detailDialogShow = true
    },
    handleExport() {
      let params = {
        ...this.searchData.form
      }
      const config = this.$commonJs.getAlarmPathConfig(this.$route.path)
      alarmWarningExport(params, `${config.wTitle}_${new Date().getTime()}.xlsx`);
    },
    handleImport() {
      console.log("等待处理")
    },
    closeDialog() {
      this.detailDialogShow = false
    },

    singleDelete(row) {
      this.$confirm(this.$t('tips.confirmDelete'), this.$t('common.tips'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      }).then(() => {
        this.loading = true
        alarmWarningDelete(row.id).then(res => {
          if (res.code == 200) {
            this.$message({
              message: this.$t('tips.deleteSuccess'),
              type: 'success'
            })
            this.search()
          } else {
            this.$message({
              message: this.$t('tips.systemException'),
              type: 'error'
            })
          }
        }).finally(final => {
          this.loading = false
        })
      })
    },
    initAlarmConfig() {
      let type = this.$route.path
      console.log("path:" + type)
      const config = this.$commonJs.getAlarmPathConfig(this.$route.path)
      this.modeType = config.modeTypeYj
      this.title = config.wTitle
    }
  },
  activated() {
    this.fetch()
  },
  created() {
    this.initAlarmConfig()
    // 获取字典值
    this.fetch()
    //预警类型
    let warnType = this.$commonJs.getAlarmPathConfig(this.$route.path).warnType
    this.warnTypeOptions = []
    this.$commonJs.filterDataDict(warnType, this.warnTypeOptions)
    this.statusOptions = []
    this.$commonJs.filterDataDict("waringStatus", this.statusOptions)
    this.disposeStatusOptions = []
    this.$commonJs.filterDataDict("disposeStatus", this.disposeStatusOptions)
    this.warnLevelOptions = []
    this.$commonJs.filterDataDict("waringLevel", this.warnLevelOptions)
    this.isTimeoutOptions = []
    this.$commonJs.filterDataDict("alarmIsTimeout", this.isTimeoutOptions)
    this.superviseStateOptions = []
    this.$commonJs.filterDataDict("superviseState",this.superviseStateOptions )
  },
  mounted() {
    this.tableMainHeight = document.getElementsByClassName('table-main')[0].clientHeight - 44 //减去顶部按钮列表的高度
  }
}
</script>

<style lang="scss" scoped>
.table-all {
  display: flex;
  flex-direction: column;
  height: 100%;

  .search-box {
    padding-bottom: 6px;
  }

  .table-box {
    padding-top: 10px;
    flex: 1;
    display: flex;
    flex-direction: column;

    .table-main {
      flex: 1;
      overflow: auto;
    }

    .table-page {
      // padding-top: 10 px;
      // padding-bottom: 10 px;
    }

    ::v-deep .pagination-container {
      text-align: right;
    }

  }
}
</style>
